<template>
  <Category :isShowTable="isShowTable" />
  <el-card style="margin: 15px 0">
    <div v-show="isShowTable">
      <el-button
        :disabled="!categoryStore.c3Id"
        type="primary"
        icon="Plus"
        @click="addAttr"
      >
        添加属性
      </el-button>
      <el-table :data="attrShowList" border style="margin: 15px 0">
        <el-table-column
          label="序号"
          width="70px"
          type="index"
        ></el-table-column>
        <el-table-column label="属性名称" prop="attrName"></el-table-column>
        <el-table-column label="属性值名称">
          <template #default="{ row }">
            <el-tag
              v-for="item in row.attrValueList"
              :key="item.id"
              type="success"
              style="margin: 5px"
            >
              {{ item.valueName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150px">
          <template #default="{ row }">
            <el-button
              size="small"
              type="warning"
              icon="Edit"
              @click="updateAttr(row)"
            ></el-button>
            <el-popconfirm
              width="220"
              confirm-button-text="确定"
              cancel-button-text="取消"
              icon="InfoFilled"
              icon-color="#626AEF"
              :title="`确定要删除${row.attrName}吗`"
              @confirm="deleteCurrentAttr(row.id)"
            >
              <template #reference>
                <el-button size="small" type="danger" icon="Delete"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-show="!isShowTable">
      <el-form style="max-width: 460px" label-width="100px">
        <el-form-item label="属性名称">
          <el-input
            ref="inputAttrName"
            size="small"
            v-model="attrParams.attrName"
            placeholder="输入属性名字"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-button
        :disabled="!attrParams.attrName"
        type="primary"
        icon="Plus"
        size="small"
        @click="addAttrValue"
      >
        添加属性值
      </el-button>
      <el-button size="small" @click="cancel">取消</el-button>
      <el-table border style="margin: 15px 0" :data="attrParams.attrValueList">
        <el-table-column
          label="序号"
          type="index"
          align="center"
          width="80px"
        ></el-table-column>
        <el-table-column label="属性值" prop="valueName">
          <template #default="{ row, $index }">
            <el-input
              :ref="(vc:any) => inputArr[$index] = vc"
              v-if="row.isFlag"
              @blur="toLook(row, $index)"
              placeholder="请输入属性值"
              size="small"
              v-model="row.valueName"
            ></el-input>
            <p v-else @click="toEdit(row, $index)">{{ row.valueName }}</p>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row, $index }">
            <el-button
              type="danger"
              size="small"
              icon="Delete"
              @click="deleteValue($index)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button
        :disabled="!attrParams.attrValueList.length"
        @click="updateAttrValue"
        type="primary"
        size="small"
      >
        保存
      </el-button>
      <el-button size="small" @click="cancel">取消</el-button>
    </div>
  </el-card>
</template>

<script lang="ts" setup>
import { nextTick, onBeforeUnmount, reactive, ref, watch, onMounted } from 'vue'
// 接口
import { getAttrData, addOrUpdateAttr, deleteAttr } from '@/api/product/attr'
// type类型
import type { AttrResponseData, Attr, AttrValue } from '@/api/product/attr/type'
// category仓库
import useCategoryStore from '@/store/modules/category'
import { ElMessage } from 'element-plus'
const categoryStore = useCategoryStore()
const attrShowList = ref<Attr[]>([])

// 切换展示按钮
const isShowTable = ref<boolean>(true)

// input聚焦数组
const inputArr = ref<any>([])
// 属性名称ref
const inputAttrName = ref()
// 收集添加or更新的attr数据
const attrParams = reactive<Attr>({
  attrName: '',
  id: '',
  categoryLevel: '',
  categoryId: '',
  attrValueList: [],
})

watch(
  () => categoryStore.c3Id,
  (cur, pre) => {
    attrShowList.value = []
    if (cur && cur !== pre) getAttrList()
  },
)
onMounted(() => getAttrList())
onBeforeUnmount(() => {
  //  初始化仓库响应式数据
  categoryStore.$reset()
})

const getAttrList = async () => {
  const { c1Id, c2Id, c3Id } = categoryStore
  const res: AttrResponseData = await getAttrData(c1Id, c2Id, c3Id)
  attrShowList.value = res.data
}
// 点击删除
const deleteCurrentAttr = async (id: any) => {
  const res = await deleteAttr(id)
  if (res.code === 200) {
    ElMessage.success('删除成功')
    getAttrList()
  }
}
// 点击修改属性
const updateAttr = (row: Attr) => {
  Object.assign(attrParams, JSON.parse(JSON.stringify(row)))
  isShowTable.value = false
  nextTick(() => {
    inputAttrName.value.focus()
  })
}
// 点击添加属性
const addAttr = () => {
  Object.assign(attrParams, {
    attrName: '',
    id: '',
    categoryLevel: 3,
    categoryId: categoryStore.c3Id,
    attrValueList: [],
  })
  isShowTable.value = false
  nextTick(() => {
    inputAttrName.value.focus()
  })
}
// 切换为编辑
const toEdit = (row: AttrValue, index: number) => {
  row.isFlag = true
  nextTick(() => {
    inputArr.value[index].focus()
  })
}
// 切换查看
const toLook = (row: AttrValue, index: number) => {
  if (!row.valueName.trim()) {
    ElMessage.warning('属性值不能为空')
    attrParams.attrValueList.splice(index, 1)
    return
  }
  const isPeat = attrParams.attrValueList.findIndex((item) => {
    if (item != row) {
      return item.valueName === row.valueName
    }
  })
  if (isPeat !== -1) {
    ElMessage.warning('属性值不能重复')
    attrParams.attrValueList.splice(index, 1)
    return
  }
  row.isFlag = false
}

// 点击取消添加属性
const cancel = () => {
  isShowTable.value = true
}
// 点击添加属性值
const addAttrValue = () => {
  attrParams.attrValueList = attrParams.attrValueList.filter(
    (item) => item.valueName,
  )
  attrParams.attrValueList.push({ valueName: '', isFlag: true })
  setTimeout(() => {
    inputArr.value[inputArr.value.length - 1]?.focus()
  }, 100)
}
// 点击删除属性值
const deleteValue = (index: any) => {
  attrParams.attrValueList.splice(index, 1)
}
// 点击保存属性值
const updateAttrValue = async () => {
  delete attrParams?.createTime
  delete attrParams?.updateTime
  attrParams.attrValueList = attrParams.attrValueList.map((item) => {
    if (!item.id) {
      return {
        valueName: item.valueName,
      }
    } else {
      return {
        attrId: item.attrId,
        valueName: item.valueName,
        id: item.id,
      }
    }
  })
  const res = await addOrUpdateAttr(attrParams)
  if (res.code === 200) {
    ElMessage.success(attrParams.id ? '修改成功' : '添加成功')
    isShowTable.value = true
    getAttrList()
  } else {
    ElMessage.error('更新失败,请重试')
  }
}
</script>

<style lang="scss" scoped></style>
